package com.ygqh.baby.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.utils.GridFSUtil;
import com.ygqh.baby.utils.ImageUtils;

@Controller
@RequestMapping("/chat/file")
public class FileController extends BaseController {

	@Value("${tempfile.path}")
	private String imageUploadTempUrl;

	@RequestMapping("/image")
	public void image(@RequestParam(required = true) String id, HttpServletResponse response) {
		GridFSDBFile file = GridFSUtil.getFileById(id);
		if (file == null) {
			logger.error("查无此图，id-->" + id);
			return;
		}
		OutputStream out = null;
		InputStream is = null;
		try {
			response.setContentType(file.getContentType());
			is = file.getInputStream();
			byte[] b = new byte[1024];
			out = response.getOutputStream();
			while (is.read(b) != -1) {
				out.write(b);
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/imageUp")
	@ResponseBody
	public JSONPObject imageUp(@RequestParam("file") MultipartFile file, String callback) throws IOException {
		if (file.getInputStream() != null) {
			String filename = file.getOriginalFilename();
			String ext = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
			String imageTmpUrl = imageUploadTempUrl + "/" + UUID.randomUUID().toString() + "" + "." + ext;
			saveFile(file.getInputStream(), imageTmpUrl);
			return new JSONPObject(callback, createFileData(imageTmpUrl, ext));
		}
		return new JSONPObject(callback, Message.error("上传失败"));
	}

	private void saveFile(InputStream inputStream, String fileName) {
		OutputStream os = null;
		try {
			byte[] bs = new byte[1024];
			int len;
			os = new FileOutputStream(fileName);
			while ((len = inputStream.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "uploadBase64Image")
	@ResponseBody
	public JSONPObject uploadBase64Image(@RequestParam("uploadFile") String uploadFile, @RequestParam(required = true) String fileName, Boolean isFill,
			HttpServletRequest request, HttpServletResponse response, String callback) throws Exception {
		if (isFill == null)
			isFill = true;
		uploadFile = uploadFile.split(",")[1];
		String ext = fileName.split("\\.")[1];
		String imageTmpUrl = imageUploadTempUrl + "/" + UUID.randomUUID().toString() + "" + "." + ext;
		ImageUtils.GenerateImage(uploadFile, imageTmpUrl);
		return new JSONPObject(callback, createFileData(imageTmpUrl, ext));
	}

	private Message createFileData(String imageTmpUrl, String ext) throws IOException {
		File file = new File(imageTmpUrl);
		imageTmpUrl = imageUploadTempUrl + "/" + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".temp." + ext;
		InputStream is = new FileInputStream(file);
		ImageUtils.scale2(is, imageTmpUrl, 0, 400, Boolean.FALSE);
		File file2 = new File(imageTmpUrl);
		GridFSFile saveFile = GridFSUtil.saveFile(file2, Boolean.FALSE);
		GridFSFile originalFile = GridFSUtil.saveFile(file, Boolean.FALSE);
		String fileId = saveFile.getId().toString();
		String originalFileId = originalFile.getId().toString();
		if (file2.exists()) {
			file2.delete();
		}
		is.close();
		if (file.exists()) {
			file.delete();
		}
		Map<String, Object> data = new HashMap<>();
		data.put("fileId", fileId);
		data.put("originalFileId", originalFileId);
		logger.info(data.toString());
		return Message.success(data);
	}
}
